from PIL import Image
import cv2
import numpy as np
import matplotlib.pyplot as plt
def match_and_mark(input_image, feature_images):

    input_img = cv2.imread(input_image)
    input_gray = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)

    match_found = False

    # Loop through each feature image
    for i, feature_path in enumerate(feature_images):
        # Read feature image and convert to grayscale
        feature_img = cv2.imread(feature_path)
        feature_gray = cv2.cvtColor(feature_img, cv2.COLOR_BGR2GRAY)

        # Perform template matching
        result = cv2.matchTemplate(input_gray, feature_gray, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

        # Define threshold for a "match"
        threshold = 0.8  # Match confidence threshold
        if max_val >= threshold:
            # Mark the matching region
            match_found = True
            top_left = max_loc
            h, w = feature_gray.shape
            bottom_right = (top_left[0] + w, top_left[1] + h)
            cv2.rectangle(input_img, top_left, bottom_right, (0, 255, 0), 3)

            # Print match confirmation for the current feature
            # print(f"Feature {i + 1} matched with confidence: {max_val:.2f}")
            return True
    # Display the result
    marked_image_rgb = cv2.cvtColor(input_img, cv2.COLOR_BGR2RGB)
    # plt.figure(figsize=(10, 10))
    # plt.imshow(marked_image_rgb)
    # plt.axis('off')
    # plt.title("Input Image with Marked Features")
    # plt.show()

    # Print result if no match is found
    if not match_found:
        # print("No features matched in the input image.")
        return False


imglist =["luo2.png","PVC-Figures-You_00024_.png","PVC-Figures-You_00022_.png","luo.png","371cf00c374e9f20370522b0d0a9866 (1).png"]
for i in imglist:
    feature_image_paths = ["image.png", "image1.png"]
    input_image_path = i

    # Call the function
    res = match_and_mark(input_image_path, feature_image_paths)
    print(str(i)+"<<<<"+str(res))



